﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Devdream.Web.Common
{
    public class Secrurity
    {
        /// <summary>
        /// 创建验证码字符
        /// </summary>
        /// <param name="length">字符长度</param>
        /// <returns>验证码字符</returns>
        public static string CreateVerificationText(int length)
        {
            char[] verification = new char[length];
            char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            Random random=new Random();
            for (int i = 0; i < length; i++)
			{
			 verification[i]=dictionary[random.Next(dictionary.Length-1)];
			}
            return new string(verification);
        }
        /// <summary>
        /// 创建验证码图片
        /// </summary>
        /// <param name="verificationText">验证码字符</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <returns></returns>
        public static Bitmap CreateVerificationImage(string verificationText,int width,int height)
        {
            Pen pen=new Pen(Color.Beige);
            Font font=new Font("Arial",16,FontStyle.Bold);
            Brush _brush = null;
            Bitmap _bitmap = new Bitmap(width,height);
            Graphics _g = Graphics.FromImage(_bitmap);
            SizeF _totalSizeF = _g.MeasureString(verificationText,font);
            SizeF _curCharSizeF;
            PointF _startPointF = new PointF((width-_totalSizeF.Width)/2,(height-_totalSizeF.Height)/2);
            //随机数产生器
            Random _random =new Random();
            _g.Clear(Color.White);
            for(int i=0;i<verificationText.Length;i++)
            {
                _brush = new LinearGradientBrush(new Point(0,0),new Point(1,1),Color.FromArgb(_random.Next(255),_random.Next(255),_random.Next(255)),Color.FromArgb(_random.Next(255),_random.Next(255),_random.Next(255)));
                _g.DrawString(verificationText[i].ToString(),font,_brush,_startPointF);
                _curCharSizeF = _g.MeasureString(verificationText[i].ToString(),font);
                _startPointF.X+= _curCharSizeF.Width;
            }
            _g.Dispose();
            return _bitmap;
        }
       /// <summary>
       /// 256位散列加密
       /// </summary>
       /// <param name="text"></param>
       /// <returns></returns>
        public static string Sha256(string text)
        {
            SHA256Managed sha = new SHA256Managed();
            byte[] cip = sha.ComputeHash(Encoding.Default.GetBytes(text));
            return Convert.ToBase64String(cip);
        }
    }
}